#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <sstream>
#include <unordered_map>
#include <fstream>


static const std::string sep = "\r\n";
static const std::string header_sep = ": ";
static const std::string wwwroot = "wwwroot";
static const std::string homepage = "index.htm";
static const std::string httpversion = "HTTP/1.0";
static const std::string space = " ";

class HttpRequest
{
private:
    std::string GetOneLine(std::string &reqstr)
    {
        if (reqstr.empty())
            return reqstr;
        auto pos = reqstr.find(sep);
        if (pos == std::string::npos)
            return std::string();

        std::string line = reqstr.substr(0, pos);
        reqstr.erase(0, pos + sep.size());
        return line.empty() ? sep : line;
    }

    bool ParseHeaderHelper(const std::string &line, std::string *k, std::string *v)
    {
        auto pos = line.find(header_sep);
        if (pos == std::string::npos)
            return false;

        *k = line.substr(0, pos);
        *v = line.substr(pos + header_sep.size());
        return true;
    }

public:
    HttpRequest() : _blank_line(sep), _path(wwwroot)
    {
    }

    void Serialize()
    {
    }

    void Derialize(std::string &reqstr)
    {
        _req_line = GetOneLine(reqstr);

        while (true)
        {
            std::string line = GetOneLine(reqstr);
            if (line.empty())
            {
                break;
            }
            else if (line == sep)
            {
                _req_text = reqstr;
                break;
            }
            else
            {
                _req_header.emplace_back(line);
            }
        }
        ParseReqLine();
        ParseHeader();
    }

    void Print()
    {
        std::cout << "====" << _req_line << std::endl;
        for (auto &header : _req_header)
        {
            std::cout << "*****" << header << std::endl;
        }
        std::cout << _blank_line;
        std::cout << "====" << _req_text << std::endl;

        std::cout << "-----------------------------------" << std::endl;
        std::cout << "method ####" << _method << std::endl;
        std::cout << "url ####" << _url << std::endl;
        std::cout << "path ####" << _path << std::endl;
        std::cout << "httpversion ####" << _version << std::endl;

        for (auto &header : _headers)
        {
            std::cout << "@@@@@@" << header.first << " - " << header.second << std::endl;
        }
    }

    bool ParseReqLine()
    {
        if (_req_line.empty())
            return false;
        std::stringstream ss(_req_line);

        ss >> _method >> _url >> _version;
        _path += _url;

        if (_path[_path.size() - 1] == '/')
        {
            _path += homepage;
        }

        return true;
    }

    bool ParseHeader()
    {
        for (auto &header : _req_header)
        {
            std::string k, v;
            if (ParseHeaderHelper(header, &k, &v))
            {
                _headers.insert(std::make_pair(k, v));
                //_headers.insert(std::pair<std::string,std::string>(k,v));
                //_headers.insert({k,v});
            }
        }
        return true;
    }
    std::string Path()
    {
        return _path;
    }
    ~HttpRequest()
    {
    }

private:
    // 原始协议内容
    std::string _req_line;
    std::vector<std::string> _req_header;
    std::string _blank_line;
    std::string _req_text;

    // 期望解析内容
    std::string _method;
    std::string _url;
    std::string _path;
    std::string _version;

    std::unordered_map<std::string, std::string> _headers;
};

class Factory
{
public:
    static std::shared_ptr<HttpRequest> BuildHttprequest()
    {
        return std::make_shared<HttpRequest>();
    }

    static std::shared_ptr<HttpResponse> BuildHttpResponse()
    {
        return std::make_shared<HttpResponse>();
    }

};

class HttpResponse
{
public:
    HttpResponse() : _version(httpversion), _blank_line(sep)
    {
    }
    void AddStatusLine(int code)
    {
        _code = code;
        _desc = "ok"; // TODO
    }

    void AdeHeader(const std::string &k, const std::string &v)
    {
        _headers[k] = v; // insert
    }
    void AddText(const std::string &text)
    {
        _resp_text = text;
    }
    std::string Serialize()
    {
        std::string _status_line = _version + space + std::to_string(_code) + space + _desc + sep;
        for (auto &header : _headers)
        {
            _resp_header.emplace_back(header.first + header_sep + header.second + sep);
        }

        std::string respstr = _status_line;
        for (auto &header : _resp_header)
        {
            respstr += header;
        }
        respstr += _blank_line;
        respstr += _resp_text;
        return respstr;
    }

    ~HttpResponse() {}

private:
    // 构建应答的必要字段
    std::string _version;
    int _code;
    std::string _desc;
    std::unordered_map<std::string, std::string> _headers;

    std::string _req_line;
    std::vector<std::string> _resp_header;
    std::string _blank_line;
    std::string _resp_text;
};

class HttpServer
{
public:
    HttpServer() 
    {}
    
    std::string ReadFileContent(const std::string& path, int* size)
    {
        //要按照二进制的方式打开
        std::ifstream in(path,std::ios::binary);
        if(in.is_open())
        {
            return std::string();
        }
        in.seekg(0,in.end);
        int filesize = in.tellg();
        in.seekg(0,in.beg);

        std::string content;
        content.resize(filesize);
        in.read((char*)content.c_str(),filesize);
        in.close();
        *size = filesize;
        return content;
    }


    std::string HandlerHttpRequest(std::string req)
    {
#ifdef TEST
        std::cout << "---------------------------------------" << std::endl;
        std::cout << req;

        std::string response = "HTTP/1.0 200 OK\r\n"; // 404 NOT Found
        response += "\r\n";
        response += "<html><body><h1>hello world, hello bite!</h1></body></html>";

        return response;
#else
        auto request = Factory::BuildHttprequest();
        request->Derialize(req);
        int contentsize;
        std::string text= ReadFileContent(request->Path(),&contentsize);

        auto response = Factory::BuildHttpResponse();
        response->AddStatusLine(200);
        response->AdeHeader("Content-Length",std::to_string(contentsize));
        response->AdeHeader("Content-Type","text/html");
        response->AddText(text);

        return response->Serialize();

#endif
    }
    ~HttpServer() {}

private:
};